<template>
  <div class="item-list">
    <div class="page-header">
      <div class="header-left">
        <h2>商品列表</h2>
      </div>
      <div class="header-right">
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedItems.length === 0">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>新建商品
        </el-button>
        <el-button type="success" @click="showBulkImportDialog">
          <el-icon><Upload /></el-icon>批量导入
        </el-button>
      </div>
    </div>

    <!-- 查询条件 -->
    <div class="search-panel">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.item_name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="品牌">
          <el-input v-model="searchForm.item_brand" placeholder="请输入品牌" clearable />
        </el-form-item>
        <el-form-item label="店铺">
          <el-select v-model="searchForm.shop_id" placeholder="请选择店铺" clearable style="width: 200px">
            <el-option
              v-for="shop in shops"
              :key="shop.id"
              :label="shop.shop_name"
              :value="shop.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><RefreshRight /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 商品列表 -->
    <div class="table-container">
      <el-table
        v-loading="loading.items"
        :data="items"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="item_name" label="商品名称" min-width="150" />
        <el-table-column prop="item_img" label="商品图片" width="100">
          <template #default="{ row }">
            <el-image 
              v-if="row.item_img" 
              :src="row.item_img" 
              style="width: 50px; height: 50px"
              :preview-src-list="[row.item_img]"
              fit="cover"
            >
              <template #error>
                <div class="image-error">无图片</div>
              </template>
            </el-image>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="item_brand" label="品牌" width="120" />
        <el-table-column prop="item_specs" label="规格" width="120" />
        <el-table-column prop="item_price" label="价格" width="100">
          <template #default="{ row }">
            {{ row.item_price ? `¥${row.item_price}` : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="base_price" label="基准价" width="100">
          <template #default="{ row }">
            {{ row.base_price ? `¥${row.base_price}` : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="base_unit" label="基准单位" width="100" />
        <el-table-column prop="shop_name" label="所属店铺" width="150" />
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" @click="showEditDialog(row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button type="danger" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 创建/编辑商品对话框 -->
    <el-dialog
      v-model="dialogs.item"
      :title="editingItem.id ? '编辑商品' : '新建商品'"
      width="750px"
    >
      <el-form
        ref="itemFormRef"
        :model="editingItem"
        :rules="itemRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="item_name">
              <el-input v-model="editingItem.item_name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="item_brand">
              <el-input v-model="editingItem.item_brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="商品图片" prop="item_img">
          <el-upload
            class="item-uploader"
            action="/api/file/upload"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
          >
            <el-image
              v-if="editingItem.item_img"
              :src="editingItem.item_img"
              class="item-image"
              fit="cover"
            />
            <el-icon v-else class="item-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议上传正方形图片，尺寸不小于300x300</div>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格" prop="item_specs">
              <el-input v-model="editingItem.item_specs" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品分类" prop="item_classification">
              <el-input v-model="editingItem.item_classification" placeholder="请输入商品分类" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="价格" prop="item_price">
              <el-input-number v-model="editingItem.item_price" :min="0" :precision="2" :step="0.01" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="基准价" prop="base_price">
              <el-input-number v-model="editingItem.base_price" :min="0" :precision="2" :step="0.01" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="基准单位" prop="base_unit">
              <el-input v-model="editingItem.base_unit" placeholder="请输入基准单位" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属店铺" prop="shop_id">
              <el-select v-model="editingItem.shop_id" placeholder="请选择店铺" style="width: 100%">
                <el-option
                  v-for="shop in shops"
                  :key="shop.id"
                  :label="shop.shop_name"
                  :value="shop.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="SKU ID" prop="sku_id">
              <el-input v-model="editingItem.sku_id" placeholder="请输入SKU ID" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.item = false">取消</el-button>
          <el-button type="primary" :loading="loading.submit" @click="handleSubmitItem">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="dialogs.bulkImport"
      title="批量导入商品"
      width="600px"
    >
      <div class="bulk-import-dialog">
        <el-alert
          type="info"
          show-icon
          :closable="false"
          title="请按照JSON格式输入商品数据，每行一个商品对象"
        />
        <p class="format-example">格式示例：<code>[{"item_name": "苹果", "item_brand": "红富士", "item_price": 5.5, "shop_id": 1}]</code></p>
        <el-input
          v-model="bulkImportData"
          type="textarea"
          :rows="10"
          placeholder="请输入JSON格式的商品数据"
          @input="validateBulkImportData"
        />
        <div v-if="bulkImportError" class="json-error">
          <el-alert
            type="error"
            show-icon
            :closable="false"
            :title="bulkImportError"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.bulkImport = false">取消</el-button>
          <el-button type="primary" :loading="loading.bulkImport" @click="handleBulkImport">
            导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Search, RefreshRight, Upload } from '@element-plus/icons-vue'
// 导入接口API
import { getItemList, createItem, updateItem, deleteItem, bulkCreateItems, bulkDeleteItems } from '@/api/item'
import { getShopList } from '@/api/shop'

// 搜索表单
const searchForm = reactive({
  item_name: '',
  item_brand: '',
  shop_id: ''
})

// 多选相关
const selectedItems = ref([])

// 状态变量
const items = ref([])
const shops = ref([])
const editingItem = ref({
  item_name: '',
  item_brand: '',
  item_specs: '',
  item_price: 0,
  item_classification: '',
  base_price: 0,
  base_unit: '',
  shop_id: '',
  shop_name: '',
  sku_id: '',
  item_img: '',
  run_id: 'manual'
})
const bulkImportData = ref('')
const bulkImportError = ref('')

// 加载状态
const loading = reactive({
  items: false,
  shops: false,
  submit: false,
  bulkImport: false,
  batchDelete: false
})

// 对话框显示状态
const dialogs = reactive({
  item: false,
  bulkImport: false
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单引用
const itemFormRef = ref(null)

// 表单验证规则
const itemRules = {
  item_name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  item_price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  shop_id: [
    { required: true, message: '请选择所属店铺', trigger: 'change' }
  ],
  sku_id: [
    { required: true, message: '请输入SKU ID', trigger: 'blur' }
  ]
}

// 图片上传相关
const handleImageSuccess = (response, file) => {
  if (response.code === 0 && response.data) {
    editingItem.value.item_img = response.data.url
  } else {
    ElMessage.error('图片上传失败')
  }
}

const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 初始化
onMounted(() => {
  fetchItemList()
  fetchShopList()
})

// 获取商品列表
const fetchItemList = async () => {
  try {
    loading.items = true
    const params = {
      keyword: searchForm.item_name,
      brand: searchForm.item_brand,
      shop_id: searchForm.shop_id,
      page: pagination.currentPage,
      page_size: pagination.pageSize
    }
    
    const response = await getItemList(params)
    items.value = response.items || []
    pagination.total = response.total || 0
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.items = false
  }
}

// 获取店铺列表
const fetchShopList = async () => {
  try {
    loading.shops = true
    const response = await getShopList()
    shops.value = response.items || []
  } catch (error) {
    console.error('获取店铺列表失败:', error)
  } finally {
    loading.shops = false
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  editingItem.value = {
    item_name: '',
    item_brand: '',
    item_specs: '',
    item_price: 0,
    item_classification: '',
    base_price: 0,
    base_unit: '',
    shop_id: '',
    shop_name: '',
    sku_id: '',
    item_img: '',
    run_id: 'manual'
  }
  dialogs.item = true
  // 确保下一个tick表单重置
  setTimeout(() => {
    itemFormRef.value?.resetFields()
  }, 0)
}

// 显示编辑对话框
const showEditDialog = (item) => {
  editingItem.value = JSON.parse(JSON.stringify(item)) // 深拷贝
  dialogs.item = true
}

// 提交商品表单
const handleSubmitItem = async () => {
  if (!itemFormRef.value) return
  
  await itemFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      loading.submit = true
      
      // 获取选中店铺的名称
      const selectedShop = shops.value.find(shop => shop.id === editingItem.value.shop_id)
      if (selectedShop) {
        editingItem.value.shop_name = selectedShop.shop_name
      }
      
      if (editingItem.value.id) {
        // 更新
        await updateItem(editingItem.value.id, editingItem.value)
        ElMessage.success('商品更新成功')
      } else {
        // 创建
        await createItem(editingItem.value)
        ElMessage.success('商品创建成功')
      }
      
      dialogs.item = false
      fetchItemList() // 刷新列表
    } catch (error) {
      console.error('提交商品信息失败:', error)
      ElMessage.error(error.response?.data?.detail || '提交失败')
    } finally {
      loading.submit = false
    }
  })
}

// 删除商品
const handleDelete = async (item) => {
  try {
    await ElMessageBox.confirm(`确定要删除商品"${item.item_name}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteItem(item.id)
    ElMessage.success('删除成功')
    fetchItemList() // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1 // 重置到第一页
  fetchItemList()
}

// 重置查询
const resetSearch = () => {
  searchForm.item_name = ''
  searchForm.item_brand = ''
  searchForm.shop_id = ''
  pagination.currentPage = 1
  fetchItemList()
}

// 分页相关
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchItemList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchItemList()
}

// 多选处理
const handleSelectionChange = (selection) => {
  selectedItems.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的${selectedItems.value.length}个商品吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    loading.batchDelete = true
    const ids = selectedItems.value.map(item => item.id)
    await bulkDeleteItems({ ids })
    ElMessage.success('批量删除成功')
    fetchItemList() // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  } finally {
    loading.batchDelete = false
  }
}

// 显示批量导入对话框
const showBulkImportDialog = () => {
  bulkImportData.value = ''
  bulkImportError.value = ''
  dialogs.bulkImport = true
}

// 验证批量导入数据
const validateBulkImportData = (value) => {
  if (!value.trim()) {
    bulkImportError.value = ''
    return
  }
  try {
    const data = JSON.parse(value)
    if (!Array.isArray(data)) {
      bulkImportError.value = '数据格式错误：应为JSON数组'
      return
    }
    for (const item of data) {
      if (!item.item_name) {
        bulkImportError.value = '数据格式错误：商品名称不能为空'
        return
      }
      if (!item.shop_id) {
        bulkImportError.value = '数据格式错误：店铺ID不能为空'
        return
      }
    }
    bulkImportError.value = ''
  } catch (error) {
    bulkImportError.value = 'JSON格式错误: ' + error.message
  }
}

// 批量导入商品
const handleBulkImport = async () => {
  if (bulkImportError.value) {
    ElMessage.warning('请先修正数据格式错误')
    return
  }
  
  if (!bulkImportData.value.trim()) {
    ElMessage.warning('请输入要导入的数据')
    return
  }
  
  try {
    loading.bulkImport = true
    const items = JSON.parse(bulkImportData.value)
    
    // 处理数据格式，确保每个字段类型正确
    const formattedItems = items.map(item => {
      const formattedItem = { ...item }
      
      // 添加默认值
      if (!formattedItem.run_id) {
        formattedItem.run_id = 'bulk_import'
      }
      
      // 确保数值类型正确
      if (formattedItem.item_price && typeof formattedItem.item_price === 'string') {
        formattedItem.item_price = parseFloat(formattedItem.item_price) || 0
      }
      if (formattedItem.base_price && typeof formattedItem.base_price === 'string') {
        formattedItem.base_price = parseFloat(formattedItem.base_price) || 0
      }
      if (formattedItem.shop_id && typeof formattedItem.shop_id === 'string') {
        formattedItem.shop_id = parseInt(formattedItem.shop_id, 10) || 0
      }
      
      return formattedItem
    })
    
    const result = await bulkCreateItems(formattedItems)
    ElMessage.success(`成功导入${result.count || formattedItems.length}条商品数据`)
    dialogs.bulkImport = false
    fetchItemList() // 刷新列表
  } catch (error) {
    console.error('批量导入失败:', error)
    ElMessage.error(error.response?.data?.detail || '批量导入失败')
  } finally {
    loading.bulkImport = false
  }
}
</script>

<style scoped>
.item-list {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0;
}

.header-right {
  display: flex;
  gap: 10px;
}

.search-panel {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.bulk-import-dialog {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.format-example {
  font-size: 14px;
  color: #606266;
}

.format-example code {
  background-color: #f5f7fa;
  padding: 2px 5px;
  border-radius: 3px;
  font-family: monospace;
}

.json-error {
  margin-top: 10px;
}

/* 图片上传相关样式 */
.item-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.item-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.item-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.item-image {
  width: 120px;
  height: 120px;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 5px;
}

.image-error {
  width: 50px;
  height: 50px;
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  color: #909399;
}
</style> 